//
//  GroupMemberListVC.swift
//  ZIMKit
//
//  Created by zego on 2024/7/25.
//

import UIKit
import Localize_Swift

class GroupMemberListVC: _ViewController {
    
    public convenience init(conversationID: String , memberList:[ZIMKitGroupMemberInfo]) {
        self.init()
        self.conversationID = conversationID
        self.memberList = memberList.filter { $0.memberRole != .robot }
        myselfGroupMemberInfo()
    }
    
    var memberList = [ZIMKitGroupMemberInfo]()
    /// 我自己的群成员信息
    var myselfGroupInfo: ZIMKitGroupMember?
    
    var conversationID: String = ""
    lazy var tableView: UITableView = {
        let tableView: UITableView = UITableView(frame: .zero, style: .plain).withoutAutoresizingMaskConstraints
        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = .clear
        tableView.register(ZIMKitGroupMemberInfoTableViewCell.self, forCellReuseIdentifier: ZIMKitGroupMemberInfoTableViewCell.reuseId)
        tableView.separatorStyle = .none
        return tableView
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBar.backgroundColor = .zim_backgroundWhite
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .zim_backgroundGray5
        setNavigationView()
        setUpSubviewsLayout()
        queryGroupMemberList()
        tableView.reloadData()
    }
    
    func setNavigationView() {
        navigationItem.title = L10n("group_member_list")
        
        let leftButton = UIButton(type: .custom)
        leftButton.setImage(loadImageSafely(with: "chat_nav_left"), for: .normal)
        leftButton.addTarget(self, action: #selector(backItemClick(_:)), for: .touchUpInside)
        leftButton.widthAnchor.constraint(equalToConstant: 40).isActive = true
        leftButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
        leftButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: -20, bottom: 0, right: 0)
        let leftItem = UIBarButtonItem(customView: leftButton)
        self.navigationItem.leftBarButtonItem = leftItem
        
        let rightButton = UIButton(type: .custom)
        rightButton.setTitle(L10n("add_member_to_group"), for: .normal)
        rightButton.setTitleColor(.zim_backgroundBlue1, for: .normal)
        rightButton.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        rightButton.addTarget(self, action: #selector(addMemberToGroupClick(_:)), for: .touchUpInside)
        rightButton.widthAnchor.constraint(equalToConstant: 40).isActive = true
        rightButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
        rightButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        let rightItem = UIBarButtonItem(customView: rightButton)
        self.navigationItem.rightBarButtonItem = rightItem
    }
    
    func setUpSubviewsLayout() {
        view.addSubview(tableView)
        NSLayoutConstraint.activate([
            tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
            tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
        ])
    }
    
    @objc func backItemClick(_ button: UIButton) {
        navigationController?.popViewController(animated: true)
    }
    
    @objc func addMemberToGroupClick(_ button: UIButton) {
        // 添加群成员
        let alertController = UIAlertController(title: L10n("add_member_title"), message: nil, preferredStyle: .alert)
        // 添加输入框
        alertController.addTextField(configurationHandler: { (textField) in
            textField.placeholder = L10n("enter_invite_member_placeholder")
            textField.keyboardType = .numberPad
        })
        let sureAction = UIAlertAction(title: L10n("common_sure"), style: .default) { [weak self] (action) in
            // 获取输入内容
            let id = alertController.textFields?.first?.text ?? ""
            // 打印或处理数据
            xLog("id: \(id)")
            
            guard let self = self else { return }
            
            self.inviteUsersIntoGroup(by: self.conversationID, userID: id) { isSuccess in
                if isSuccess {
                    self.queryGroupMemberList()
                }
            }
        }
        // 添加取消按钮
        let cancelAction = UIAlertAction(title: L10n("common_title_cancel"), style: .cancel)
        // 将按钮添加至弹窗
        alertController.addAction(sureAction)
        alertController.addAction(cancelAction)
        present(alertController)
        
        //        let popView: ZIMKitInviteUserInGroupView = ZIMKitInviteUserInGroupView.init(conversationID: conversationID)
        //        popView.sureBlock = { isSuccess in
        //            self.queryGroupMemberList()
        //        }
        //        popView.showView()
    }
    
    /// 我自己的群成员信息
    func myselfGroupMemberInfo() {
        ZIMKit.queryGroupMemberInfo(by: String(UserProfile.userId), groupID: conversationID) { member, error in
            // ZIMKitGroupMember
            self.myselfGroupInfo = member
            if member.role != .owner {
                self.navigationItem.rightBarButtonItem = nil
            }
        }
    }
    
    func queryGroupMemberList() {
        ZIMKit.queryGroupMemberList(by: conversationID, maxCount: 99999, nextFlag: 0) { [weak self] memberList, nextFlag, error in
            if error.code.rawValue == 0 {
                self?.memberList = memberList
                self?.tableView.reloadData()
                
            } else {
                print("[ERROR] queryGroupMemberList code = \(error.code)")
            }
        }
    }
    
    /// 添加群成员
    /// - Parameters:
    ///   - groupID: 群 id
    ///   - userID: 用户 id
    func inviteUsersIntoGroup(by groupID: String, userID: String, callback: ((Bool) -> Void)? = nil) {
        ZIMKit.inviteUsersIntoGroup(by: groupID, userIDs: [userID]) { groupID, userList, errorUserList, error in
            if error.code.rawValue == 0 {
                YLHUD.showMessage(L10n("invite_success"))
            } else if (error.code.rawValue == 6000011) {
                print("[ERROR] inviteUsersIntoGroup error: code = \(error.code)")
                YLHUD.showHint(.error, L10n("user_not_register"))
                
            } else if error.code.rawValue == 6000522 {
                YLHUD.showHint(.error, L10n("already_belong"))
            }
            callback?(error.code.rawValue == 0)
        }
    }
}

extension GroupMemberListVC :UITableViewDelegate,UITableViewDataSource {
    // MARK: - UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return memberList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: ZIMKitGroupMemberInfoTableViewCell.reuseId, for: indexPath) as! ZIMKitGroupMemberInfoTableViewCell
        let model:ZIMKitGroupMemberInfo = memberList[indexPath.row]
        cell.selectionStyle = .none
        cell.configure(with: model.userName, avatarUrl: model.userAvatarUrl)
        cell.lineView.isHidden = (indexPath.row == (self.memberList.count - 1) ? true : false)
        return cell
    }
    
    // MARK: - UITableViewDelegate
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 68
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        
        guard let myselfGroupInfo = myselfGroupInfo else { return nil }
        
        // 非群主不让移出群成员
        if myselfGroupInfo.role != .owner { return nil }
        
        let member = memberList[indexPath.row]
        if member.userID == myselfGroupInfo.id {
            // 我自己不让移除
            return nil
        }
        
        // 创建删除按钮
        let deleteAction = UIContextualAction(style: .destructive, title: "移出成员".localized(.call)) { (action, view, completionHandler) in
            YLAlert(controller: self, title: "确定要移出成员".localized(.call) + "\(member.userName)", actionTitles: ["确定".localized()]) { action, index in
                ZIMKit.removeGroupMembers(by: self.conversationID, userIDs: [member.userID]) { groupID, userIds, errorUserList, error in
                    if errorUserList.count == 0 {
                        // 执行删除操作，例如从数据源中移除项目
                        self.memberList.remove(at: indexPath.row)
                        tableView.deleteRows(at: [indexPath], with: .automatic)
                    } else {
                        xLog("移出成员失败")
                    }
                }
            }
            completionHandler(true)
        }
        
        // 配置删除按钮的图标（可选）
        // deleteAction.image = UIImage(systemName: "trash")
        
        // 创建并返回 UISwipeActionsConfiguration 对象
        let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
        return configuration
    }
    
}
